<template>
  <div class="archive-approval-request-submit-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>提交档案审批请求</span>
      </div>
      
      <!-- 请求类型选择 -->
      <el-form :model="requestForm" ref="requestForm" label-width="120px" :rules="rules">
        <el-form-item label="请求类型" prop="requestType">
          <el-radio-group v-model="requestForm.requestType" @change="handleRequestTypeChange">
            <el-radio label="confidentiality_level_adjustment">密级调整申请</el-radio>
            <el-radio label="restricted_archive_access">受限档案查看申请</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 密级调整申请表单 -->
        <div v-if="requestForm.requestType === 'confidentiality_level_adjustment'">
          <el-form-item label="选择档案" prop="archiveId">
            <el-select v-model="requestForm.archiveId" placeholder="请选择要申请的档案" filterable @change="handleArchiveChange">
              <el-option
                v-for="item in archivesForSelection"
                :key="item.archiveId"
                :label="item.title + ' (ID: ' + item.archiveId + ')'"
                :value="item.archiveId">
              </el-option>
            </el-select>
          </el-form-item>
          
          <!-- 显示选中档案的详细信息 -->
          <div v-if="selectedArchive" class="selected-archive-info">
            <h4>档案详情</h4>
            <el-descriptions :column="2" border size="small">
              <el-descriptions-item label="档案标题">{{ selectedArchive.title }}</el-descriptions-item>
              <el-descriptions-item label="档案类型">{{ selectedArchive.archiveType }}</el-descriptions-item>
              <el-descriptions-item label="物理位置">{{ selectedArchive.physicalLocation }}</el-descriptions-item>
              <el-descriptions-item label="创建时间">{{ selectedArchive.createdAt }}</el-descriptions-item>
              <el-descriptions-item label="可见范围">{{ selectedArchive.visibleScope }}</el-descriptions-item>
              <el-descriptions-item label="状态">{{ selectedArchive.status }}</el-descriptions-item>
            </el-descriptions>
            
            <!-- 文档内容展示 -->
            <div class="ocr-content-section" v-if="selectedArchive.ocrContent">
              <h5>文档内容</h5>
              <el-input
                type="textarea"
                :rows="4"
                v-model="selectedArchive.ocrContent"
                :readonly="true"
                placeholder="无文档内容">
              </el-input>
            </div>
            <div class="ocr-content-section" v-else>
              <h5>文档内容</h5>
              <el-alert
                title="该档案没有文档内容"
                type="info"
                :closable="false"
                show-icon>
              </el-alert>
            </div>
          </div>
          
          <el-form-item label="当前密级">
            <el-input v-model="currentSecurityLevel" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="新密级" prop="requestedValue">
            <el-select v-model="requestForm.requestedValue" placeholder="请选择新的保密等级">
              <el-option label="绝密" value="绝密"></el-option>
              <el-option label="机密" value="机密"></el-option>
              <el-option label="秘密" value="秘密"></el-option>
              <el-option label="内部" value="内部"></el-option>
              <el-option label="公开" value="公开"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="notes">
            <el-input type="textarea" v-model="requestForm.notes" placeholder="请输入申请备注"></el-input>
          </el-form-item>
        </div>

        <!-- 受限档案申请表单 -->
        <div v-if="requestForm.requestType === 'restricted_archive_access'">
          <el-form-item label="选择受限档案" prop="archiveId">
            <el-select 
              v-model="requestForm.archiveId" 
              placeholder="请选择要申请查看的受限档案" 
              filterable 
              @change="handleRestrictedArchiveChange">
              <el-option
                v-for="archive in restrictedArchives"
                :key="archive.archiveId"
                :label="`${archive.title} (${archive.securityLevel})`"
                :value="archive.archiveId">
                <span style="float: left">{{ archive.title }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ archive.securityLevel }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          
          <!-- 显示选中受限档案信息 -->
          <div v-if="selectedRestrictedArchive" class="selected-archive-info">
            <h4>档案详情</h4>
            <el-descriptions :column="2" border size="small">
              <el-descriptions-item label="档案标题">{{ selectedRestrictedArchive.title }}</el-descriptions-item>
              <el-descriptions-item label="档案类型">{{ selectedRestrictedArchive.archiveType }}</el-descriptions-item>
              <el-descriptions-item label="保密等级">
                <el-tag :type="getSecurityLevelType(selectedRestrictedArchive.securityLevel)">
                  {{ selectedRestrictedArchive.securityLevel }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="物理位置">{{ selectedRestrictedArchive.physicalLocation || '无' }}</el-descriptions-item>
            </el-descriptions>
          </div>

          <el-form-item label="申请原因" prop="reason">
            <el-input 
              type="textarea" 
              :rows="4" 
              v-model="requestForm.reason" 
              placeholder="请详细说明申请查看该受限档案的原因和用途">
            </el-input>
          </el-form-item>
          <el-form-item label="预计使用期限" prop="expectedDuration">
            <el-select v-model="requestForm.expectedDuration" placeholder="请选择预计使用期限">
              <el-option label="1天" value="1天"></el-option>
              <el-option label="3天" value="3天"></el-option>
              <el-option label="1周" value="1周"></el-option>
              <el-option label="2周" value="2周"></el-option>
              <el-option label="1个月" value="1个月"></el-option>
              <el-option label="其他" value="其他"></el-option>
            </el-select>
          </el-form-item>
          <el-alert
            title="提示：受限档案申请需要企业领导审批，审批通过后方可查看"
            type="info"
            :closable="false"
            show-icon>
          </el-alert>
        </div>

        <el-form-item>
          <el-button type="primary" @click="submitRequest('requestForm')">提交申请</el-button>
          <el-button @click="resetForm('requestForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import service from '@/utils/request';

export default {
  name: 'ArchiveApprovalRequestSubmit',
  data() {
    return {
      requestForm: {
        archiveId: null,
        requestType: 'confidentiality_level_adjustment',
        requestedValue: '',
        notes: '',
        reason: '',
        expectedDuration: ''
      },
      rules: {
        requestType: [{ required: true, message: '请选择请求类型', trigger: 'change' }],
        archiveId: [{ required: true, message: '请选择档案', trigger: 'change' }],
        requestedValue: [{ required: true, message: '请选择新的密级', trigger: 'change' }],
        reason: [
          { required: true, message: '请输入申请原因', trigger: 'blur' },
          { min: 10, message: '申请原因不能少于10个字符', trigger: 'blur' }
        ],
        expectedDuration: [{ required: true, message: '请选择预计使用期限', trigger: 'change' }]
      },
      archivesForSelection: [],
      currentSecurityLevel: '',
      selectedArchive: null,
      restrictedArchives: [],
      selectedRestrictedArchive: null
    };
  },
  created() {
    this.fetchArchivesForSelection();
    this.fetchRestrictedArchives();
  },
  methods: {
    fetchArchivesForSelection() {
      service.get('/archive/list', {
        params: {
          pageNum: 1,
          pageSize: 9999
        }
      })
      .then(res => {
        if (res.data.code === 200) {
          this.archivesForSelection = res.data.data.records;
        } else {
          this.$message.error(res.data.message || '获取档案列表失败');
        }
      })
      .catch(error => {
        console.error("Error fetching archives for selection:", error);
        this.$message.error('获取档案列表失败');
      });
    },
    
    fetchRestrictedArchives() {
      service.get('/archive/list', {
        params: {
          pageNum: 1,
          pageSize: 9999
        }
      })
      .then(res => {
        if (res.data.code === 200) {
          // 过滤出受限档案（保密等级不是公开的档案）
          this.restrictedArchives = res.data.data.records.filter(archive => 
            archive.securityLevel && archive.securityLevel !== '公开'
          );
        } else {
          this.$message.error(res.data.message || '获取受限档案列表失败');
        }
      })
      .catch(error => {
        console.error("Error fetching restricted archives:", error);
        this.$message.error('获取受限档案列表失败');
      });
    },

    handleRequestTypeChange(requestType) {
      // 重置表单相关字段
      this.requestForm.archiveId = null;
      this.requestForm.requestedValue = '';
      this.requestForm.notes = '';
      this.requestForm.reason = '';
      this.requestForm.expectedDuration = '';
      this.currentSecurityLevel = '';
      this.selectedArchive = null;
      this.selectedRestrictedArchive = null;
      
      // 更新验证规则
      this.updateValidationRules(requestType);
    },

    updateValidationRules(requestType) {
      if (requestType === 'confidentiality_level_adjustment') {
        this.rules = {
          requestType: [{ required: true, message: '请选择请求类型', trigger: 'change' }],
          archiveId: [{ required: true, message: '请选择档案', trigger: 'change' }],
          requestedValue: [{ required: true, message: '请选择新的密级', trigger: 'change' }]
        };
      } else if (requestType === 'restricted_archive_access') {
        this.rules = {
          requestType: [{ required: true, message: '请选择请求类型', trigger: 'change' }],
          archiveId: [{ required: true, message: '请选择档案', trigger: 'change' }],
          reason: [
            { required: true, message: '请输入申请原因', trigger: 'blur' },
            { min: 10, message: '申请原因不能少于10个字符', trigger: 'blur' }
          ],
          expectedDuration: [{ required: true, message: '请选择预计使用期限', trigger: 'change' }]
        };
      }
    },

    handleArchiveChange(archiveId) {
      const selectedArchive = this.archivesForSelection.find(archive => archive.archiveId === archiveId);
      if (selectedArchive) {
        this.currentSecurityLevel = selectedArchive.securityLevel;
        this.selectedArchive = selectedArchive;
      } else {
        this.currentSecurityLevel = '';
        this.selectedArchive = null;
      }
    },

    handleRestrictedArchiveChange(archiveId) {
      const selectedRestrictedArchive = this.restrictedArchives.find(archive => archive.archiveId === archiveId);
      if (selectedRestrictedArchive) {
        this.selectedRestrictedArchive = selectedRestrictedArchive;
      } else {
        this.selectedRestrictedArchive = null;
      }
    },

    submitRequest(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            let url = '';
            let requestData = {};

            if (this.requestForm.requestType === 'confidentiality_level_adjustment') {
              // 密级调整申请
              url = '/archive-approval/submit';
              requestData = {
                archiveId: this.requestForm.archiveId,
                requestType: this.requestForm.requestType,
                requestedValue: this.requestForm.requestedValue,
                notes: this.requestForm.notes
              };
            } else if (this.requestForm.requestType === 'restricted_archive_access') {
              // 受限档案申请
              url = '/restricted-archive-request/submit';
              requestData = {
                archiveId: this.requestForm.archiveId,
                reason: this.requestForm.reason,
                expectedDuration: this.requestForm.expectedDuration
              };
            }

            const response = await service.post(url, requestData);
            if (response.data.code === 200) {
              this.$message.success('申请提交成功');
              this.resetForm(formName);
            } else {
              this.$message.error(response.data.message || '申请提交失败');
            }
          } catch (error) {
            console.error("Error submitting request:", error);
            this.$message.error('申请提交失败');
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.currentSecurityLevel = '';
      this.selectedArchive = null;
      this.selectedRestrictedArchive = null;
      this.requestForm.requestType = 'confidentiality_level_adjustment';
      this.updateValidationRules('confidentiality_level_adjustment');
    },

    getSecurityLevelType(level) {
      const typeMap = {
        '绝密': 'danger',
        '机密': 'warning',
        '秘密': 'primary',
        '内部': 'info',
        '公开': 'success'
      };
      return typeMap[level] || 'info';
    }
  }
}
</script>

<style scoped>
.archive-approval-request-submit-container {
  padding: 20px;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}
.box-card {
  width: 100%;
}

.selected-archive-info {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.selected-archive-info h4 {
  margin-bottom: 15px;
  color: #606266;
}

.ocr-content-section {
  margin-top: 15px;
}

.ocr-content-section h5 {
  margin-bottom: 10px;
  color: #606266;
  font-size: 14px;
}
</style> 